package com.pillar.game;

import com.pillar.AppConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@AllArgsConstructor
public class StartGame implements CommandLineRunner {

    private final AppConfig appConfig;


    private void start() {
        log.info("正在启动游戏服务器");
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup work = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, work);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new NioWebSocketChannelInitializer(work));
            Channel channel = bootstrap.bind(appConfig.getPort()).sync().channel();
            log.info("游戏启动成功{}",channel);
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.info("游戏启动异常：" + e);
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
            log.info("游戏服务已关闭");
        }
    }


    @Override
    public void run(String... args) throws Exception {
            start();
    }
}
